package cn.cloudtogo.server.redis;

import cn.cloudtogo.common.ExternalDatasourceSpringTemplateContextRefresher;
import cn.cloudtogo.common.model.DatasourceTypes;
import cn.cloudtogo.common.model.ExternalDatasourceDao;
import cn.cloudtogo.common.model.ExternalDatasourceModel;
import cn.cloudtogo.common.types.RequestHeaderObject;
import cn.cloudtogo.support.redis.RedisConnectionHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yaolianhua789@gmail.com
 **/
@Component
@Slf4j
public class SpringRedisTemplateContextRefresher implements ExternalDatasourceSpringTemplateContextRefresher {

    private final SpringRedisTemplateContext springRedisTemplateContext;
    private final ExternalDatasourceDao datasourceService;

    public SpringRedisTemplateContextRefresher(SpringRedisTemplateContext springRedisTemplateContext,
                                               ExternalDatasourceDao datasourceService) {
        this.springRedisTemplateContext = springRedisTemplateContext;
        this.datasourceService = datasourceService;
    }

    @Override
    public synchronized void refresh() {
        List<ExternalDatasourceModel> models = datasourceService.list()
                .stream()
                .filter(e -> Objects.equals(e.getType(), DatasourceTypes.Redis))
                .collect(Collectors.toList());

        for (ExternalDatasourceModel redisModel : models) {
            JedisConnectionFactory jedisConnectionFactory = RedisConnectionHelper.getJedisConnectionFactory(redisModel.getUrl());
            RedisTemplate<String, Object> redisTemplate = RedisConnectionHelper.getRedisTemplate(jedisConnectionFactory);

            RequestHeaderObject requestHeaderObject = RequestHeaderObject.ofModel(redisModel);

            springRedisTemplateContext.putRedisTemplate(requestHeaderObject, redisTemplate);

        }

        List<String> projects = models.stream()
                .map(ExternalDatasourceModel::getProject)
                .collect(Collectors.toList());
        log.debug("refresh spring redisTemplate context from datasource '{}'", projects);
    }
}
